// pages/Detail/detail.js
const WxParse = require('../Common/wxParse/wxParse.js');
const Controller = require('../controllers/controllers.js').controller;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 轮播图当前索引
        currentIndex: 0,
        // 折叠面板当前的数据
        activeNames: [],
        //商品id
        id: '',
        info: {},
        verification: [],
        cartNum: 0,
        list: [],
        //库存
        stock: 0,
        discountPrice: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        if (options.id) {
            this.setData({
                id: options.id
            })
        }
        this.getInfo()
        this.getList()
            //  获取当前页面路径

    },
    //格式化富文本
    formatRichText(html) {
        if (html) {
            let newContent = html.replace(/<img[^>]*>/gi, function(match, capture) {
                match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
                match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
                match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
                return match;
            });
            newContent = newContent.replace(/<table[^>]*>/gi, function(match, capture) {
                match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
                match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
                match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
                return match;
            });
            newContent = newContent.replace(/style="[^"]+"/gi, function(match, capture) {
                match = match.replace(/width:[^;]+;/gi, 'max-width:100%;vertical-align:middle;')
                return match;
            });
            // newContent = newContent.replace(/<br[^>]*\/>/gi, '');
            newContent = newContent.replace(/\<img/gi,
                '<img style="max-width:100%;vertical-align:middle;"');
            return newContent;
        }
    },

    //查看尺码
    goSize() {
        wx.navigateTo({
            url: `/pages/Detail/size?id=${this.data.id}`,
        })
    },

    //选择规格
    select(e) {
        let type = e.currentTarget.dataset.type
        let index = e.currentTarget.dataset.index
        let stock = e.currentTarget.dataset.stock
        let info = this.data.info
        let discountPrice = ''
        let id = ''
        if (stock == 0) {
            return
        }



        info.goodsSpecList[type].attributeList.forEach((item, i) => {
            item.select = false
        })
        info.goodsSpecList[type].attributeList[index].select = !info.goodsSpecList[type].attributeList[index].select
        let attrIds = []
        info.goodsSpecList.forEach((item, t) => {
            item.attributeList.forEach((ite) => {
                if (ite.select) {
                    attrIds.push(ite.id)
                    id = ite.id
                }
            })
        })
        for (let i in info.goodsSpecList) {
            if (i != type) {
                info.goodsSpecList[i].attributeList.forEach(it => {
                    let a = this.data.verification.filter(item => item.attrIds.indexOf(it.id) != -1 && this.forFlag(item.attrIds, i))
                    if (a.length > 0) {
                        for (let e in a) {
                            if (a[e].stock > 0) {
                                it.stock = a[e].stock
                                break
                            } else {
                                it.stock = a[e].stock
                            }
                        }
                    } else {
                        it.stock = 0
                    }
                })
            }
        }
        if (info.goodsSpecList.length == attrIds.length) {
            
            let q = this.data.verification.findIndex(item => this.forFlag(item.attrIds, -1))
             
            console.log('q==>',q)
            console.log('verification==>',this.data.verification)
            discountPrice = this.data.verification[q].discountPrice
        }

        this.setData({
            info,
            'info.discountPrice':discountPrice
        })
    },

    //遍历判断
    forFlag(ids, index) {
        let attrIds = []
        this.data.info.goodsSpecList.forEach((item, t) => {
            item.attributeList.forEach((ite) => {
                if (ite.select && index != t) {
                    attrIds.push(ite.id)
                }
            })
        })
        let arr = attrIds.filter(ite => ids.indexOf(ite) != -1)
        return arr.length == attrIds.length
    }, 
    //获取商品详情
    getInfo() {
        Controller.goodsdetail({
            goodsId: this.data.id
        }).then(res => {
            let info = res.data.baseData
            if(info.subTitle){
                info.subTitle=info.subTitle.replace(/\n/g,'<p></p>')
            }
            
            if (info.imgUrls.indexOf(',') != '-1') {
                info.imgList = info.imgUrls.split(',')
            } else {
                info.imgList = [info.imgUrls]
            }
            let verification = info.specAttributePriceList
            info.goodsSpecList.forEach((item,index)=> {
                item.attributeList.forEach(ite => {
                    ite.select = false
                    let a = verification.filter(item => item.attrIds.indexOf(ite.id) != -1)
                    if (a.length > 0) {
                        for (let e in a) {
                            if (a[e].stock > 0) {
                                ite.stock = a[e].stock
                                return
                            } else {
                                ite.stock = a[e].stock
                            }
                        }
                    } else {
                        ite.stock = 0
                    }
                })
            })
            
        
            for(let index in  [0,1]){
                
            
            

                  
                    
                    let item=info.goodsSpecList[index]

                    console.log('info.item',item)

                     for( let  v   of  item.attributeList){
                         console.log('v.stock',v.stock)
                           if(v.stock){
                            v.select=true

                              this.data.info=info
                              this.setDefaultSelect(index,info,verification)

                            break

                           }

                     }  

                  

                    
                

            }

            
            this.setData({
                info,
                verification
            })
            if (info.content) {
                WxParse.wxParse('content', 'html', this.formatRichText(info.content), this, 5);
            }
            if (info.afterSaleInfo) {
                WxParse.wxParse('afterSaleInfo', 'html', this.formatRichText(info.afterSaleInfo), this, 5);
            }
            if (info.washInfo) {
                WxParse.wxParse('washInfo', 'html', this.formatRichText(info.washInfo), this, 5);
            }
        })
    },
      // 设置默认值
    setDefaultSelect(type,info,verification){

    for(let i in  info.goodsSpecList){

   
        if (i != type) {
            info.goodsSpecList[i].attributeList.forEach(it => {
                let a = verification.filter(item => item.attrIds.indexOf(it.id) != -1 && this.forFlag(item.attrIds, i))
                if (a.length > 0) {
                    for (let e in a) {
                        if (a[e].stock > 0) {
                            it.stock = a[e].stock
                            break
                        } else {
                            it.stock = a[e].stock
                        }
                    }
                } else {
                    it.stock = 0
                }
            })
        }


    }
       
      


    },
    //获取商品列表
    getList() {
        Controller.goodslist({
            isRecommend: 1,
            page: 1,
        }).then(res => {
            let list = res.data.baseData.list
            this.setData({
                list
            })
        })
    },
    //跳转详情
    goDetail(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: `/pages/Detail/detail?id=${id}`,
        })
    },
    //获取购物车数量
    geCartcount() {
        Controller.cartcount().then(res => {
            this.setData({
                cartNum: res.data.baseData
            })
        })
    },
    //页面跳转
    goPage(e) {
        let url = e.currentTarget.dataset.url
        wx.switchTab({
            url
        })
    },
    //下单
    placeOrder() {
        let info = this.data.info
        let specs = []
        let attrIds = []
        info.goodsSpecList.forEach(item => {
            item.attributeList.forEach(ite => {
                if (ite.select) {
                    specs.push(item.name + ':' + ite.name)
                    attrIds.push(ite.id)
                }
            })
        })
        if (attrIds.length < info.goodsSpecList.length) {
            wx.showToast({
                title: '请先选择规格',
                icon: 'none'
            })
            return
        }

        let index = this.data.verification.findIndex(item => item.attrIds === attrIds.join(','))
        let num = index != -1 ? this.data.verification[index].stock : 0
        let goodsSpecAttributePriceId = index != -1 ? this.data.verification[index].id : ''

        console.log(num, index, this.data.verification)

        if (num == 0) {
            wx.showToast({
                title: '暂无库存',
                icon: 'none'
            })
            return
        }
        wx.navigateTo({
            url: `/pages/Pay/pay?goodsId=${this.data.id}&specs=${specs.join(',')}&goodsSpecAttributePriceId=${goodsSpecAttributePriceId}&type=goods`
        })
    },
    //加入购物车
    joinCart() {
        let info = this.data.info
        let specs = []
        let attrIds = []
        info.goodsSpecList.forEach(item => {
            item.attributeList.forEach(ite => {
                if (ite.select) {
                    specs.push(item.name + ':' + ite.name)
                    attrIds.push(ite.id)
                }
            })
        })
        if (attrIds.length < info.goodsSpecList.length) {
            wx.showToast({
                title: '请先选择规格',
                icon: 'none'
            })
            return
        }



        let index = this.data.verification.findIndex(item => item.attrIds === attrIds.join(','))

      


        let num = index != -1 ? this.data.verification[index].stock : 0
        let goodsSpecAttributePriceId = index != -1 ? this.data.verification[index].id : ''
        if (num == 0) {
            wx.showToast({
                title: '暂无库存',
                icon: 'none'
            })
            return
        }
        Controller.addOrUpdate({
            goodsId: this.data.id,
            specs: specs.join(','),
            attrIds: attrIds.join(','),
            amount: 1,
            goodsSpecAttributePriceId,
            type: 1,
        }).then(res => {
            wx.showToast({
                title: '加入成功',
                icon: 'none'
            })
            this.geCartcount()
        })

    },
    change(e) {
        let current = e.detail.current
        console.log('e==>', e)
        this.setData({
            currentIndex: current
        })
    },
    handleCollapse(event) {
        this.setData({
            activeNames: event.detail,
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },
    //触发分享接口

    onShareAppMessage() {
        let id = this.data.id
        let title = this.data.info.title
        return {
            title,
            path: '"pages/Detail/detail?id=' + id,
        }
    },


    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.geCartcount()
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    }


})